﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using Selenium;

namespace WebAutomation.Browsers.FireFox
{
    public class FireFoxBrowser:WebBrowserObject
    {
        private string _javaDirectoryLocation = @"C:\Program Files (x86)\Java\jre6\bin";
        private string rcServerLocation = Directory.GetCurrentDirectory() + "\\selenium-server-standalone-2.25.0.jar";
        protected static DefaultSelenium _firefox;
        private int _processId = 0;
        public FireFoxBrowser()
        {
            var listOfBrowsers = System.Diagnostics.Process.GetProcessesByName("firefox");
            foreach (var items in listOfBrowsers)
            {
                items.Kill();
            }
            if (!Directory.Exists(_javaDirectoryLocation))
            {
                throw new Exception("You must install Java jre6.");
            }
            else
            {
                if (!File.Exists(rcServerLocation))
                {
                    throw new Exception("The Selenuim RC Server jar file could not found in (" + rcServerLocation + ").");
                }
                else
                {
                    string _javaFileLocation = _javaDirectoryLocation + "\\java.exe";
                    string seleniumParameters = rcServerLocation;
                    System.Diagnostics.Process process = new Process();
                    ProcessStartInfo processStartInfo = new ProcessStartInfo();
                    processStartInfo.Arguments = " -jar " + seleniumParameters;
                    processStartInfo.FileName = _javaFileLocation;
                    _processId = System.Diagnostics.Process.Start(processStartInfo).Id;
                    System.Threading.Thread.Sleep(1000);
                }


            }

            //start up RC Server
            //IWebDriver test=new FirefoxDriver();

        }

        private string _getFindValue(WatiN.Core.Constraints.Constraint find)
        {
            string returnValue = "";
            string[] findByArray = find.ToString().Replace("Attribute ", "").Replace(" equals ", "^").Split('^');
            string findBy = findByArray[0].Replace("'", "");
            string findValue = findByArray[1].Replace("'", "");
            returnValue = findValue;
            return returnValue;

        }

        public override int ProcessID
        {
            get { return _processId; }
        }

        public override WebBrowserObject.ElementProperties Button(WatiN.Core.Constraints.Constraint find)
        {
            ElementProperties returnValue = new ElementProperties();
            string xPathLocator = "";
            bool isFound = _getElementXPath(find, ref xPathLocator);
            if (isFound)
            {
                returnValue.Element = xPathLocator;
                returnValue.Exists = true;
            }


            return returnValue;


        }

        public override void ButtonWaitUntilExists(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override void DivWaitUntilAttributeValue(string divID, string attributeName, string expectedValue)
        {
            throw new NotImplementedException();
        }

        public override void WaitForComplete()
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties CheckBox(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override object Div(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override object DomContainer()
        {
            throw new NotImplementedException();
        }

        public override void CaptureWebPageAsImage(string imageFileName, string imageQualityString, int imageQuality)
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties Element(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties Element()
        {
            throw new NotImplementedException();
        }

        public override Dictionary<int, object> Frames()
        {
            Dictionary<int, object> returnValue = new Dictionary<int, object>();
            string frameSrc = "";
            try
            {
                _firefox.SelectFrame("Index=0");
                frameSrc = _firefox.GetAttribute("id");
            }catch
            {
                
            }

            return returnValue;
        }

        public override void WaitForCompleteIFrame(int iframeIndex, int secondsToWait)
        {
            //_firefox.WaitForFrameToLoad()
        }

        public override WebBrowserObject.ElementProperties ElementIFrame(int iframeIndex, string idOrNameOrClassOrValue)
        {
            throw new NotImplementedException();
        }

        public override void GoTo(string url)
        {
            if (_firefox == null)
            {
                _firefox = new DefaultSelenium("localhost", 4444, "*firefox", url);
                _firefox.Start();
            }
            _firefox.Open(url);
            _firefox.WaitForPageToLoad("5000");
        }

        public override string Html()
        {
            return _firefox.GetHtmlSource();
        }

        public override string HtmlIFrame(int iframeIndex)
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties Link(string attributeValue)
        {
            ElementProperties returnValue = new ElementProperties();
            string xPathLocator = "";
            bool isFound = _getElementLinkXPath(attributeValue, ref xPathLocator);
            if (isFound)
            {
                returnValue.Element = xPathLocator;
                returnValue.Exists = true;
            }


            return returnValue;
        }

        public override Dictionary<int, object> FrameLinks(int iframeIndex)
        {
            throw new NotImplementedException();
        }

        public override string GetIFrameLinkAttributeValue(int iframeIndex, int linkIndex, string attributeName)
        {
            throw new NotImplementedException();
        }

        public override string GetIFrameLinkClassName(int iframeIndex, int linkIndex)
        {
            throw new NotImplementedException();
        }

        public override void RunScript(string scriptToRun)
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties SelectList(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override void CheckBoxCheck(object checkBox, string valueOrId)
        {
            throw new NotImplementedException();
        }

        public override void ElementClick(object element)
        {
            throw new NotImplementedException();
        }

        public override bool SelectListSelect(object element, string selectListValue)
        {
            throw new NotImplementedException();
        }

        public override void ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle windowShowStyle)
        {
           
        }


        private bool _getElementLinkXPath(string attributeToGet, ref string xPathLocator)
        {
            string id = attributeToGet;
            bool returnValue = false;
            returnValue = _firefox.IsElementPresent("//a[@id='" + id + "']");
            xPathLocator = "//a[@id='" + id + "']";
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//a[@name='" + id + "']");
                xPathLocator = "//a[@name='" + id + "']";
            }
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//a[@class='" + id + "']");
                xPathLocator = "//a[@class='" + id + "']";
            }
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//a[@value='" + id + "']");
                xPathLocator = "//a[@value='" + id + "']";
            }
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//a[@href='" + id + "']");
                xPathLocator = "//a[@value='" + id + "']";
            }

            return returnValue;
        }

        private bool _getElementXPath(WatiN.Core.Constraints.Constraint find, ref string xPathLocator)
        {
            string id = _getFindValue(find);
            bool returnValue = false;
            returnValue = _firefox.IsElementPresent("//input[@id='" + id + "']");
            xPathLocator = "//input[@id='" + id + "']";
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//input[@name='" + id + "']");
                xPathLocator = "//input[@name='" + id + "']";
            }
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//input[@class='" + id + "']");
                xPathLocator = "//input[@class='" + id + "']";
            }
            if (!returnValue)
            {
                returnValue = _firefox.IsElementPresent("//input[@value='" + id + "']");
                xPathLocator = "//input[@value='" + id + "']";
            }

            return returnValue;
        }

        

        public override WebBrowserObject.ElementProperties TextField(WatiN.Core.Constraints.Constraint find)
        {
            ElementProperties returnValue = new ElementProperties();
            string xPathLocator = "";
            bool isFound = _getElementXPath(find, ref xPathLocator);
            if (isFound)
            {
                returnValue.Element = xPathLocator;
                returnValue.Exists = true;
            }


            return returnValue;
        }

        public override WebBrowserObject.ElementProperties TextFieldIFrame(int iframeIndex, WatiN.Core.Constraints.Constraint find)
        {
            
            throw new NotImplementedException();
        }

        public override void TypeText(object textField, string textValueToType, WebBrowserObject browserObject)
        {
            _firefox.Type(textField.ToString(), textValueToType);
            _firefox.Highlight(textField.ToString());
            Thread.Sleep(500);
        }

        public override WebBrowserObject.ElementProperties ButtonIFrame(int iframeIndex, WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override void ButtonClick(object buttonField)
        {
            _firefox.Click(buttonField.ToString());
            Thread.Sleep(7000);
           
        }

        public override void ButtonMouseDown(object buttonField)
        {
            _firefox.Click(buttonField.ToString());
            Thread.Sleep(7000);
        }

        public override void ButtonMouseUp(object buttonField)
        {
            _firefox.Click(buttonField.ToString());
            Thread.Sleep(7000);
        }

        public override string GetLinkAttributeValue(object link, string attributeToGet)
        {
            string returnValue = "";
            string attributeXpath = link.ToString()+"/@"+attributeToGet;

            try
            {
                returnValue = _firefox.GetAttribute(attributeXpath);
            }catch{}
            return returnValue;
        }

        public override void LinkClick(object link)
        {
            _firefox.Click(link.ToString());
            Thread.Sleep(5000);
        }

        public override Dictionary<int, WebBrowserObject.ElementProperties> Elements()
        {
            throw new NotImplementedException();
        }

        public override string GetIFrameAttributeValue(int iframeIndex, string attributeName)
        {
            throw new NotImplementedException();
        }

        public override bool ElementExist(object element)
        {
            throw new NotImplementedException();
        }

        public override WebBrowserObject.ElementProperties RadioButton(WatiN.Core.Constraints.Constraint find)
        {
            throw new NotImplementedException();
        }

        public override void RadioButtonCheck(object radioButton, string valueOrId)
        {
            throw new NotImplementedException();
        }

        public override bool Dispose()
        {
            try
            {
                _firefox.ShutDownSeleniumServer();
                System.Diagnostics.Process[] listOfBrowsers = System.Diagnostics.Process.GetProcessesByName("firefox");
                foreach (var items in listOfBrowsers)
                {
                    items.Kill();
                }

                listOfBrowsers = System.Diagnostics.Process.GetProcessesByName("java");
                foreach (var items in listOfBrowsers)
                {
                    items.Kill();
                }

            }
            catch
            {
                return false;
            }

            return true;
        }

        public override WebBrowserObject.ElementProperties GetLinkByText(string text, int index)
        {
            throw new NotImplementedException();
        }

        public override void WinFormType(int winHandle, string textBoxId, string textToType)
        {
            throw new NotImplementedException();
        }
        public override void KeyPressEnter(object textField, string keyName, WebBrowserObject browserObject)
        {
            throw new NotImplementedException();
        }

        public override void Refresh(string keys)
        {
            throw new NotImplementedException();

        }
    }
}
